package com.cook.controller;

import com.cook.dto.recipes.RecipesDTO;
import com.cook.result.Result;
import com.cook.service.RecipesService;
import com.cook.vo.recipes.RecipeDetailVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/recipes")
@Slf4j
public class RecipesController {

    @Autowired
    private RecipesService recipesService;

    /**
     * 根据用户ID查询食谱列表
     * @param userId 用户ID
     * @return 食谱列表
     */
    @GetMapping("/user/recipes")
    public Result<Map<String, Object>> getRecipesByUserIdParam(@RequestParam Long userId,
                                                          @RequestParam(defaultValue = "1") Integer pageNum,
                                                          @RequestParam(defaultValue = "20") Integer pageSize) {
        log.info("根据用户ID查询食谱列表（参数方式）: {}", userId);

        try {
            Map<String, Object> recipes = recipesService.getRecipesByUserIdWithPage(userId,pageNum,pageSize);
            return Result.success(recipes);
        } catch (IllegalArgumentException e) {
            log.warn("参数错误: {}", e.getMessage());
            return Result.error(400, e.getMessage());
        } catch (Exception e) {
            log.error("查询食谱列表失败: ", e);
            return Result.error(500, "查询食谱列表失败");
        }
    }

    /**
     * 分页查询所有食谱
     */
    @GetMapping("/all")
    public Result<Map<String, Object>> getAllRecipesWithPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        log.info("分页查询所有食谱: pageNum={}, pageSize={}", pageNum, pageSize);

        try {
            Map<String, Object> result = recipesService.getAllRecipesWithPage(pageNum, pageSize);
            return Result.success(result);
        } catch (IllegalArgumentException e) {
            log.warn("参数错误: {}", e.getMessage());
            return Result.error(400, e.getMessage());
        } catch (Exception e) {
            log.error("查询食谱列表失败: ", e);
            return Result.error(500, "查询食谱列表失败");
        }
    }

    /**
     * 根据标题搜索食谱
     */
    @GetMapping("/search")
    public Result<Map<String, Object>> searchRecipesByTitle(
            @RequestParam String title,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        log.info("搜索食谱: title={}, pageNum={}, pageSize={}", title, pageNum, pageSize);

        try {
            Map<String, Object> result = recipesService.searchRecipesByTitle(title, pageNum, pageSize);
            return Result.success(result);
        } catch (IllegalArgumentException e) {
            log.warn("参数错误: {}", e.getMessage());
            return Result.error(400, e.getMessage());
        } catch (Exception e) {
            log.error("搜索食谱失败: ", e);
            return Result.error(500, "搜索食谱失败");
        }
    }

    /**
     * 查询食谱详情
     * @return 食谱列表
     */
    @GetMapping("/{recipeId}")
    public Result<RecipeDetailVO> getRecipeById(@PathVariable Long recipeId) {
        log.info("根据ID查询食谱详情: {}", recipeId);

        try {
            RecipeDetailVO recipe = recipesService.getRecipeById(recipeId);
            return Result.success(recipe);
        } catch (IllegalArgumentException e) {
            log.warn("参数错误: {}", e.getMessage());
            return Result.error(400, e.getMessage());
        } catch (RuntimeException e) {
            log.warn("查询失败: {}", e.getMessage());
            return Result.error(404, e.getMessage());
        } catch (Exception e) {
            log.error("查询食谱详情失败: ", e);
            return Result.error(500, "服务器内部错误");
        }
    }

    /**
     * 创建食谱
     * @param recipesDTO
     * @return
     */
    @PostMapping
    public Result<Long> createRecipe(@RequestBody RecipesDTO recipesDTO) {
        log.info("创建菜谱: title={}", recipesDTO.getTitle());
        Long recipeId = recipesService.createRecipe(recipesDTO);
        return Result.success(recipeId);
    }

    /**
     * 更新食谱
     * @param recipesDTO
     * @return
     */
    @PutMapping
    public Result<Boolean> updateRecipe(@RequestBody RecipesDTO recipesDTO) {
        log.info("更新食谱: {}", recipesDTO.getRecipeId());

        try {
            boolean success = recipesService.updateRecipe(recipesDTO);
            if (success) {
                return Result.success("更新成功", true);
            } else {
                return Result.error(500, "更新失败");
            }
        } catch (IllegalArgumentException e) {
            log.warn("参数错误: {}", e.getMessage());
            return Result.error(400, e.getMessage());
        } catch (RuntimeException e) {
            log.warn("更新失败: {}", e.getMessage());
            return Result.error(404, e.getMessage());
        } catch (Exception e) {
            log.error("更新食谱失败: ", e);
            return Result.error(500, "更新食谱失败");
        }
    }

    /**
     * 删除食谱
     * @param recipeId
     * @param userId
     * @return
     */
    @DeleteMapping("/{recipeId}")
    public Result<Boolean> deleteRecipe(@PathVariable Long recipeId, @RequestParam Long userId) {
        log.info("删除食谱: {}, 用户: {}", recipeId, userId);

        try {
            boolean success = recipesService.deleteRecipe(recipeId, userId);
            if (success) {
                return Result.success("删除成功", true);
            } else {
                return Result.error(403, "删除失败或无权限");
            }
        } catch (IllegalArgumentException e) {
            log.warn("参数错误: {}", e.getMessage());
            return Result.error(400, e.getMessage());
        } catch (Exception e) {
            log.error("删除食谱失败: ", e);
            return Result.error(500, "删除食谱失败");
        }
    }
}
